package com.rssreader.client.mvc.views;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.rssreader.client.components.FeedPanel;
import com.rssreader.client.grids.ItemGrid;
import com.rssreader.client.mvc.controllers.FeedController;
import com.rssreader.client.mvc.events.AppEvents;
import com.rssreader.shared.model.Feed;

public class FeedView extends View {
    private final FeedPanel feedPanel = new FeedPanel();

    public FeedView(FeedController controller) {
	super(controller);
    }

    @Override
    protected void handleEvent(AppEvent event) {
	EventType eventType = event.getType();
	if (eventType.equals(AppEvents.Init)) {
	    onInit(event);
	} else if (eventType.equals(AppEvents.FeedSelected)) {
	    onFeedSelected(event);
	}
    }

    private void onInit(AppEvent event) {
	Dispatcher.forwardEvent(new AppEvent(AppEvents.FeedPanelReady, feedPanel));
    }

    // 用來響應FeedSelected事件，通過傳入的event獲得Feed
    private void onFeedSelected(AppEvent event) {
	final Feed feed = event.getData();

	// 將Feed物件作為參數創建一個ItemGird
	final ItemGrid itemGrid = new ItemGrid(feed);

	// 創建一個TabItem，並設置一些屬性
	TabItem tabItem = new TabItem(feed.getTitle());
	tabItem.setId(feed.getUuid());
	tabItem.setData("feed", feed);

	// 將先前新建的ItemGrid加到TabItem裡
	tabItem.add(itemGrid);
	tabItem.addListener(Events.Select, new Listener<TabPanelEvent>() {
	    // 選中之後的tab會清空item selection
	    @Override
	    public void handleEvent(TabPanelEvent be) {
		itemGrid.resetSelection();
		Dispatcher.forwardEvent(new AppEvent(AppEvents.TabSelected, feed));
	    }
	});

	tabItem.setClosable(true);
	// 將tabItem加到feedPanel裡
	feedPanel.addTab(tabItem);
    }
}
